package xyz.chaobei.thread.simple;

/**
 * @copyright (C), 2015-2020
 * @fileName: CountObj 一个计数器类，
 * @author: MRC
 * @date: 2021/1/26 21:23
 * @description:
 */
public class CountObj {

    private int count = 0;

    public void add(int n) {
        synchronized (this) {
            count += n;
        }
    }

    // 等效于以下一个写法
    public void sub(int b) {
        synchronized (this) {
            count -= b;
        }
    }

//    public synchronized void sub(int b) {
//        count -= b;
//    }

    public int getCount() {
        return this.count;
    }

    /**
     * 静态方法锁定的是类的Class对象
     */
    public static synchronized void test() {
        // 等效于这种写法
        synchronized (CountObj.class) {

        }
    }

}

class CountThreadA extends Thread {

    private CountObj obj;

    public CountThreadA(CountObj obj) {
        this.obj = obj;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            obj.add(1);
        }
        System.out.println("CountThreadA is end count=" + obj.getCount());
    }
}

class CountThreadB extends Thread {

    private CountObj obj;

    public CountThreadB(CountObj obj) {
        this.obj = obj;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            obj.sub(1);
        }
        System.out.println("CountThreadA is end count=" + obj.getCount());
    }
}

